package com.bana.sys.utils;

import com.alibaba.fastjson.JSONObject;
import com.bana.sys.code.SystemLogType;
import com.bana.sys.service.LogService;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @Resource
    private LogService logService;

    /**
     * 所有异常报错
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value=Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
    {
        String content=String.format("%s %s",request.getServletPath(),exception);
        logService.insertSystemLog(Token.SystemToken, SystemLogType.Exception,content,null);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("application/json;charset=UTF-8");
        JSONObject object=new JSONObject();
        object.put("message",exception.getMessage());
        try {
            response.getOutputStream().write(object.toJSONString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
